package org.wmine.core;

import java.awt.*;
import java.awt.event.*;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import java.util.*;
import java.sql.*;

import java.util.Enumeration;
import org.wmine.data.*;
import org.wmine.preprocess.PreprocessPanel;

import javax.swing.table.DefaultTableModel;


import java.io.*;

import java.lang.String;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import com.sun.org.apache.xerces.internal.parsers.XMLDocumentParser;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;


import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;


public class XmlConvert 
{
		
		private Document xmlDocument;
		private String xmlFilePath;
		
		String namesof[]=new String[100];
		private static ArrayList<String> tupleData;
		private static ArrayList<String>  lstTuple;
	
		private Map<String,String> colInfo;
		Statement statement;
		public static Vector attributename = new Vector();
		public static Vector attributtype = new Vector();
		public static Vector vecColName=new Vector();
		public static Vector vecColType=new Vector();
		public static Vector v=new Vector();
		private static String xTablename,xColname;
		public static StringWriter xmlString=new StringWriter();
		
		public XmlConvert(String tablename)
		{
			System.out.print("in xml cont"+tablename);
			xTablename=tablename;
		}
		
		public XmlConvert(String tablename,StringBuffer colname)
		{
		
			xTablename=tablename;
			xColname=colname.toString();
			System.out.println("tablename"+xTablename +"and Colnames"+ xColname);
			
			String filename=JOptionPane.showInputDialog("Enter filename");
			
			if(filename!=null)
			{
				String Filename=filename+".xml";
				System.out.println(Filename);
				PreprocessPanel.com1.addItem(Filename);
				getValuesDb(Filename);				
				
				
			}
		
		}
	
		public static void setValues(String tablename,StringBuffer colname) 
		{
			xTablename=tablename;
			xColname=colname.toString();
			System.out.println("tablename"+xTablename +"and Colnames"+ xColname);
		
		}	
		
		/**
		 *  
		 * @return Returns the tupledata in the form of the Iterator
		 */
		public static Iterator<String> getAllTupleData() {
			return tupleData.iterator();
			}
		
		/**
		 *  
		 * @return Returns the attribute names in the form of the Iterator
		 */
	
		public static Iterator<String> getAllAttributes() {
			return attributename.iterator();
			}
			
		/**
		 *  
		 * @return Returns the tupledata from table in the form of the Iterator
		 */	
		public static Iterator<String> getAllTupleTableData() {
			return  lstTuple.iterator();
			}
	
		
		/**
		 *  
		 * @return Returns the colnames from table in the form of the Iterator
		 */	
		
		public static Iterator<String>  getAllTableAttributes() {
			return vecColName.iterator();
			}
				
				
		// writes the new xml file
		public void writeDefaultConfigurationFile(int nCols,int j,Iterator<String> attributeIterator,Iterator<String> tupleIterator) throws FileNotFoundException {
			writeConfiguration(buildDefaultConfiguration(nCols,j,attributeIterator,tupleIterator),xmlFilePath);
		}

		
		public void saveConfiguration() throws FileNotFoundException {
			writeConfiguration(xmlDocument,xmlFilePath);
		}

		private void writeConfiguration(Document xmlDocument,String nameOfFile) throws FileNotFoundException {
			//System.out.println("in writeconfiguration");
			FileOutputStream fileOutputStream = new FileOutputStream(nameOfFile);  
			DOMSource domSource = new DOMSource(xmlDocument);
			//StreamResult streamResult = new StreamResult(fileOutputStream);
			StreamResult res=new StreamResult(xmlString);
			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer serializer = null;
			
			try {
				serializer = tf.newTransformer();
				serializer.setOutputProperty(OutputKeys.INDENT,"yes");
				serializer.transform(domSource, res);
				//System.out.println("in end of writeconfiguration");
				} 
				catch (TransformerConfigurationException e) {
					e.printStackTrace();
				}
				catch (TransformerException e) {
					e.printStackTrace();
				}
				System.out.println("===="+xmlString);
				String ss=xmlString.toString();
				ProjectManager.getUniqueInstance().writeFile(nameOfFile,ss,"preprocess","","");
				System.out.println(ss);
		}
	
	//this function creates new xml file
	
		public Document buildDefaultConfiguration(int nCols,int j,Iterator<String> attributeIterator,Iterator<String> tupleIterator) 
		{
				String noOfatt=""+nCols;
				String noOftuples=""+j;
				Iterator<String> aa = attributeIterator,bb = tupleIterator;
				
				String tupleName,attributeName;
				
 
				Document xmlDefaultDocument = null;
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				DocumentBuilder builder = null;
				
				Element e2 = null,e3 = null,e4 = null,e5 = null,e6 = null,e7 = null,e8 = null,e9 = null,e10 = null,e11 = null;
				Node nameoftable = null,no = null, name1= null,t= null,size2= null,type1= null;
 
				System.out.println("in Defaultwriteconfiguration3");
				try {
						builder = factory.newDocumentBuilder();
					}
				catch(ParserConfigurationException ee3) 
					{
					ee3.printStackTrace();
					}
				
				
				DOMImplementation impl = builder.getDOMImplementation();
		
				System.out.println("in Defaultwriteconfiguration5");
				xmlDefaultDocument =impl.createDocument(null, "dataset", null);
				System.out.println("in Defaultwriteconfiguration5");

				//		Root element.
				Element root = xmlDefaultDocument.getDocumentElement();
				e2 = xmlDefaultDocument.createElementNS(null, "table");
				nameoftable = xmlDefaultDocument.createTextNode(xTablename);
				e3 = xmlDefaultDocument.createElementNS(null, "tablename");
				System.out.println("in Defaultwriteconfiguration5");
				e3.appendChild(nameoftable);
				
				e2.appendChild(e3);
		
				e4 = xmlDefaultDocument.createElementNS(null, "attributes");
				e5 = xmlDefaultDocument.createElementNS(null, "size");
				no = xmlDefaultDocument.createTextNode(noOfatt);
				
				e5.appendChild(no);
				e4.appendChild(e5);
				e2.appendChild(e4);
				
				int tt=0;
					while(aa.hasNext()) {
						attributeName = aa.next();
						System.out.println(attributeName+"in while attribute names Again");
						e6 = xmlDefaultDocument.createElementNS(null, "attribute");
						e7 = xmlDefaultDocument.createElementNS(null, "name");
						name1= xmlDefaultDocument.createTextNode(attributeName);
						e7.appendChild(name1);
						e8 = xmlDefaultDocument.createElementNS(null, "type");
						String typeofatt = attributtype.get(tt).toString();
						type1= xmlDefaultDocument.createTextNode(typeofatt);
						e8.appendChild(type1);
						e6.appendChild(e7);
						e6.appendChild(e8);
						e4.appendChild(e6);
						tt++;
						}
			/*	for(int jj=0;jj<vecColType.size();jj++)
				{
					e6 = xmlDefaultDocument.createElementNS(null, "attribute");
					e7 = xmlDefaultDocument.createElementNS(null, "name");
					//name1= xmlDefaultDocument.createTextNode(attributeName);
					String name2=vecColName.get(jj).toString();
					System.out.print("NAME"+name2);
					name1= xmlDefaultDocument.createTextNode(name2);
					e7.appendChild(name1);
					e8 = xmlDefaultDocument.createElementNS(null, "type");
					String typeofatt = vecColType.get(jj).toString();
					System.out.print("TYPE"+typeofatt);
					type1= xmlDefaultDocument.createTextNode(typeofatt);
					e8.appendChild(type1);
					e6.appendChild(e7);
					e6.appendChild(e8);
					e4.appendChild(e6);
					
				}*/
					
	           e9 = xmlDefaultDocument.createElementNS(null, "tuples");
	           e2.appendChild(e9);
	
	           e10 = xmlDefaultDocument.createElementNS(null, "size");
	           size2= xmlDefaultDocument.createTextNode(noOftuples);
	           e10.appendChild(size2);
	           
	           e9.appendChild(e10);

	           		while(bb.hasNext()) {
	           			tupleName = bb.next();
	           			System.out.println(tupleName+"Again");
	           			e11 = xmlDefaultDocument.createElementNS(null, "tuple");
	           			t = xmlDefaultDocument.createTextNode(tupleName);
	           			e11.appendChild(t);
		       			e9.appendChild(e11);
	           		}
		       root.appendChild(e2);
		      System.out.println("in the end of Defaultwriteconfiguration");
		
		      	return xmlDefaultDocument;
		}
	
//		function for creating xml file for Database	
		public boolean createXML(String filename,int nCols,int j,Iterator<String> attributeIterator,Iterator<String> tupleIterator) throws IOException 
		{

				xmlFilePath=filename;
				if(new File(xmlFilePath).exists())
				{
					JOptionPane.showMessageDialog(null,"The Specified File Already Exists!!!");
					System.out.println("File already Exists");
				}
				else {
					try {
						writeDefaultConfigurationFile(nCols,j,attributeIterator,tupleIterator);
						System.out.println("in Defaultwriteconfiguration7");
						JOptionPane.showMessageDialog(null,"The File "+filename+".xml Created Successfully!!!!!!!!");
						} 
					catch (FileNotFoundException e) {
							e.printStackTrace();
			 			}
					catch (IOException e) {
						System.out.println("in exception3writeconfiguration");
						e.printStackTrace();
						}
				      }

			return true;
		}


	//this function fetches the values from database
		
		public void getValuesDb(String filename)
		{
			try{
				DatabaseManager databaseManager = DatabaseManager.getInstance();
				Connection connection = databaseManager.getConnection();
				tupleData= new ArrayList<String>();
				statement = connection.createStatement();	
				String names="Select "+xColname+" From "+xTablename;
				ResultSet resultset = statement.executeQuery(names);
				ResultSetMetaData metadata = resultset.getMetaData();
				int nCols = metadata.getColumnCount();
					for(int n=1;n<=nCols;n++)
					{
						String name = metadata.getColumnName(n);
						String type = metadata.getColumnTypeName(n);
						attributename.add(name);
						attributtype.add(type);
					}
						
				int j=0;
					while(resultset.next())
					{
						String data="";
						j++;
						int i=1;
						do{
				   	   	  data+=resultset.getString(i)+",";
				   	   	  i++;
						  }while(i<=nCols);
					tupleData.add(data);
			}
			
	    	System.out.println("Total no Of attribute;"+nCols);	
			System.out.println("Total no Of tuples;"+j);	
			System.out.println(" attribute names and Type");
			Iterator<String> attributeIterator = XmlConvert.getAllAttributes();
//			System.out.println("Tuples:");	
			Iterator<String> tupleIterator = XmlConvert.getAllTupleData();
			boolean f=false;
			
			f=createXML(filename,nCols,j,attributeIterator,tupleIterator);
		}
			catch(SQLException e)
			{
				System.out.println("Error");
				e.printStackTrace();
			}
			catch(IOException ie)
			{
				System.out.println("Error");
				ie.printStackTrace();
			}				
		
	}
		
	//function for creating xml file for Table	
	
	public void CreateTableXML(String filename,int cols,int rows,Iterator<Attribute> itrAttr,DefaultTableModel dtm)
	{
		while(itrAttr.hasNext())
		{
			Attribute s=itrAttr.next();
			vecColName.add(s.getAttributeName());
			vecColType.add(s.getAttributeType());
		}
		
		lstTuple=new ArrayList<String>();
		if(dtm.getRowCount()>0)
		{
			for(int i=0;i<rows;i++)
			{	
				String s=new String();
				for(int j=0;j<cols;j++)
				{
					if(dtm.getValueAt(i,j).toString().equals("?") || dtm.getValueAt(i,j).toString().trim().equals(""))
						s+="null,";
					else
						s+=dtm.getValueAt(i,j).toString()+",";
				}
				lstTuple.add(s);
			}
		}
		
		Iterator<String> tupleIterator = XmlConvert. getAllTupleTableData();
		Iterator<String> attributeIterator = XmlConvert.getAllTableAttributes();
		String Filename=filename+".xml";
		
		xmlFilePath=Filename;
		
		if(new File(xmlFilePath).exists())
	 	{
	 		JOptionPane.showMessageDialog(null,"The Specified File Already Exists!!!");
	 		System.out.println("File already Exists");
	 	}
		else
		{
			try {
					writeDefaultConfigurationFile(cols,rows,attributeIterator,tupleIterator);
					System.out.println("in Defaultwriteconfiguration7");
			}
			catch (FileNotFoundException e) {
				e.printStackTrace();
		 	}catch (IOException e) {
		 		System.out.println("in exception3writeconfiguration");
			 	e.printStackTrace();
		 	}
		
		}

	}
 //new function for creating a xml using for loop
	public Document build(int nCols,int j,Iterator<String> tupleIterator) 
	{
			String noOfatt=""+nCols;
			String noOftuples=""+j;
			Iterator<String> bb = tupleIterator; 
			//aa = attributeIterator,
			
			String tupleName,attributeName;
			

			Document xmlDefaultDocument = null;
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = null;
			
			Element e2 = null,e3 = null,e4 = null,e5 = null,e6 = null,e7 = null,e8 = null,e9 = null,e10 = null,e11 = null;
			Node nameoftable = null,no = null, name1= null,t= null,size2= null,type1= null;

			System.out.println("in Defaultwriteconfiguration3");
			try {
					builder = factory.newDocumentBuilder();
				}
			catch(ParserConfigurationException ee3) 
				{
				ee3.printStackTrace();
				}
			
			
			DOMImplementation impl = builder.getDOMImplementation();
	
			System.out.println("in Defaultwriteconfiguration5");
			xmlDefaultDocument =impl.createDocument(null, "dataset", null);
			//xmlString.append(xmlDefaultDocument.toString());
			
			System.out.println("in Defaultwriteconfiguration5");

			//		Root element.
			Element root = xmlDefaultDocument.getDocumentElement();
			e2 = xmlDefaultDocument.createElementNS(null, "table");
			nameoftable = xmlDefaultDocument.createTextNode(xTablename);
			e3 = xmlDefaultDocument.createElementNS(null, "tablename");
			System.out.println("in Defaultwriteconfiguration5");
			e3.appendChild(nameoftable);
			
			e2.appendChild(e3);
	
			e4 = xmlDefaultDocument.createElementNS(null, "attributes");
			e5 = xmlDefaultDocument.createElementNS(null, "size");
			no = xmlDefaultDocument.createTextNode(noOfatt);
			
			e5.appendChild(no);
			e4.appendChild(e5);
			e2.appendChild(e4);
			
			int tt=0;
				/*while(aa.hasNext()) {
					attributeName = aa.next();
					System.out.println(attributeName+"in while attribute names Again");
					e6 = xmlDefaultDocument.createElementNS(null, "attribute");
					e7 = xmlDefaultDocument.createElementNS(null, "name");
					name1= xmlDefaultDocument.createTextNode(attributeName);
					e7.appendChild(name1);
					e8 = xmlDefaultDocument.createElementNS(null, "type");
					String typeofatt = attributtype.get(tt).toString();
					type1= xmlDefaultDocument.createTextNode(typeofatt);
					e8.appendChild(type1);
					e6.appendChild(e7);
					e6.appendChild(e8);
					e4.appendChild(e6);
					tt++;
					}*/
			System.out.println("Before For loop############ "+vecColName);
			System.out.println("Before For loop############ "+vecColType);
			for(int jj=0;jj<vecColType.size();jj++)
			{
				e6 = xmlDefaultDocument.createElementNS(null, "attribute");
				e7 = xmlDefaultDocument.createElementNS(null, "name");
				//name1= xmlDefaultDocument.createTextNode(attributeName);
				String name2=vecColName.get(jj).toString();
				System.out.print("NAME"+name2);
				name1= xmlDefaultDocument.createTextNode(name2);
				e7.appendChild(name1);
				e8 = xmlDefaultDocument.createElementNS(null, "type");
				String typeofatt = vecColType.get(jj).toString();
				System.out.print("TYPE"+typeofatt);
				type1= xmlDefaultDocument.createTextNode(typeofatt);
				e8.appendChild(type1);
				e6.appendChild(e7);
				e6.appendChild(e8);
				e4.appendChild(e6);
				
			}
				
           e9 = xmlDefaultDocument.createElementNS(null, "tuples");
           e2.appendChild(e9);

           e10 = xmlDefaultDocument.createElementNS(null, "size");
           size2= xmlDefaultDocument.createTextNode(noOftuples);
           e10.appendChild(size2);
           
           e9.appendChild(e10);

           		while(bb.hasNext()) {
           			tupleName = bb.next();
           			System.out.println(tupleName+"Again");
           			e11 = xmlDefaultDocument.createElementNS(null, "tuple");
           			t = xmlDefaultDocument.createTextNode(tupleName);
           			e11.appendChild(t);
	       			e9.appendChild(e11);
           		}
	       root.appendChild(e2);
	      System.out.println("in the end of Defaultwriteconfiguration");
	
	      	return xmlDefaultDocument;
	}
	
	/*public static Iterator<Attribute> getCols() {
		return v.iterator();
	}*/
//createxml1
	public void CreateTableXML1(String filename,int cols,int rows,Iterator<Attribute> itrAttr,DefaultTableModel dtm)
	{
		//for(int ii=0;ii<dtm.getColumnCount();ii++)
		//{
			Iterator<Attribute> itr=itrAttr;
			//Iterator<Attribute> itr = getCols();
			while(itr.hasNext())
			{
				Attribute s=itr.next();
				for(int ii=0;ii<dtm.getColumnCount();ii++)
				{
					if(s.getAttributeName().equals(dtm.getColumnName(ii)))
				
					{
						
					//	v.add(s);
						vecColName.add(s.getAttributeName());
						vecColType.add(s.getAttributeType());
					}
				}
			}
		//}
		System.out.println("******"+vecColName+"\n******"+vecColType);
		lstTuple=new ArrayList<String>();
		if(dtm.getRowCount()>0)
		{
			for(int i=0;i<dtm.getRowCount();i++)
			{	
				String s=new String();
				for(int j=0;j<dtm.getColumnCount();j++)
				{
					if(dtm.getValueAt(i,j).toString().equals("?") || dtm.getValueAt(i,j).toString().trim().equals(""))
						s+="null,";
					else
						s+=dtm.getValueAt(i,j).toString()+",";
				}
				lstTuple.add(s);
			}
		}
		
		Iterator<String> tupleIterator = XmlConvert. getAllTupleTableData();
		//Iterator<String> attributeIterator = XmlConvert.getAllTableAttributes();
		String Filename=filename+".xml";
		
		xmlFilePath=Filename;
		
		if(new File(xmlFilePath).exists())
	 	{
	 		JOptionPane.showMessageDialog(null,"The Specified File Already Exists!!!");
	 		System.out.println("File already Exists");
	 	}
		else
		{
			try {
					writeDefaultConfigurationFile1(dtm.getColumnCount(),dtm.getRowCount(),tupleIterator);
					System.out.println("in Defaultwriteconfiguration7");
			}
			catch (FileNotFoundException e) {
				e.printStackTrace();
		 	}catch (IOException e) {
		 		System.out.println("in exception3writeconfiguration");
			 	e.printStackTrace();
		 	}
		
		}

	}
	//new writecong
	public void writeDefaultConfigurationFile1(int nCols,int j,Iterator<String> tupleIterator) throws FileNotFoundException {
		writeConfiguration1(build(nCols,j,tupleIterator),xmlFilePath);
	}

	
	public void saveConfiguration1() throws FileNotFoundException {
		writeConfiguration(xmlDocument,xmlFilePath);
	}

	private void writeConfiguration1(Document xmlDocument,String nameOfFile) throws FileNotFoundException {
		//System.out.println("in writeconfiguration");
		FileOutputStream fileOutputStream = new FileOutputStream(nameOfFile);  
		DOMSource domSource = new DOMSource(xmlDocument);
		//StreamResult streamResult = new StreamResult(fileOutputStream);
		//
		StreamResult streamresult = new StreamResult(xmlString);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = null;
		
		try {
			/*serializer = tf.newTransformer();
			serializer.setOutputProperty(OutputKeys.INDENT,"yes");
			serializer.transform(domSource, streamResult);
			//System.out.println("in end of writeconfiguration");
			/*} 
		try {*/
			serializer = tf.newTransformer();
			serializer.setOutputProperty(OutputKeys.INDENT,"yes");
			serializer.transform(domSource, streamresult);
			
		} 
			catch (TransformerConfigurationException e) {
				e.printStackTrace();
			}
			catch (TransformerException e) {
				e.printStackTrace();
			}
			String ss=xmlString.toString();
			ProjectManager.getUniqueInstance().writeFile(nameOfFile,ss,"preprocess","","");
			System.out.println(ss);
			
	}
	
	public void CreateTableXML2(String filename,Iterator<Attribute> itrAttr,DefaultTableModel dtm,String technique,String type,String colname)
	{
		//for(int ii=0;ii<dtm.getColumnCount();ii++)
		//{
			Iterator<Attribute> itr=itrAttr;
			//Iterator<Attribute> itr = getCols();
			int cnt=0;
			while(itr.hasNext())
			{
				Attribute s=itr.next();
				for(int ii=0;ii<dtm.getColumnCount();ii++)
				{
					if(s.getAttributeName().equals(dtm.getColumnName(ii)))
					{
						vecColName.add(s.getAttributeName());
						vecColType.add(s.getAttributeType());
						cnt++;
					}
					
				}
			}
			if(cnt<dtm.getColumnCount())
			{
				if(technique.equals("Discretization") || technique.equals("Generalization"))
					vecColName.add("Class");
				else
					//vecColName.add(technique+"_"+s.getAttributeName());
					vecColName.add(technique+"_"+colname);
				vecColType.add(type);
			}
		//}
		System.out.println("******"+vecColName+"\n******"+vecColType);
		lstTuple=new ArrayList<String>();
		if(dtm.getRowCount()>0)
		{
			for(int i=0;i<dtm.getRowCount();i++)
			{	
				String s=new String();
				for(int j=0;j<dtm.getColumnCount();j++)
				{
					if(dtm.getValueAt(i,j).toString().equals("?") || dtm.getValueAt(i,j).toString().trim().equals(""))
						s+="null,";
					else
						s+=dtm.getValueAt(i,j).toString()+",";
				}
				lstTuple.add(s);
			}
		}
		
		Iterator<String> tupleIterator = XmlConvert. getAllTupleTableData();
		//Iterator<String> attributeIterator = XmlConvert.getAllTableAttributes();
		String Filename=filename+".xml";
		
		xmlFilePath=Filename;
		
		if(new File(xmlFilePath).exists())
	 	{
	 		JOptionPane.showMessageDialog(null,"The Specified File Already Exists!!!");
	 		System.out.println("File already Exists");
	 	}
		else
		{
			try {
					writeDefaultConfigurationFile1(dtm.getColumnCount(),dtm.getRowCount(),tupleIterator);
					System.out.println("in Defaultwriteconfiguration7");
			}
			catch (FileNotFoundException e) {
				e.printStackTrace();
		 	}catch (IOException e) {
		 		System.out.println("in exception3writeconfiguration");
			 	e.printStackTrace();
		 	}
		
		}

	}
	
	

}	
		
		
	


















	


